﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

/// <summary>
/// 剪羊毛
/// </summary>
public class CutSheepFeather 
{

    //场景物体
    private GameObject sceneObj;

    private GameObject sheepSpawn;

    //private GameObject sheepFeatherPoints;

    private List<GameObject> sheepList = new List<GameObject>();//羊群

    private List<GameObject> featherList1 = new List<GameObject>();//白羊毛
    private List<GameObject> featherList2 = new List<GameObject>();//灰羊毛
    private List<GameObject> featherList = new List<GameObject>();//总羊毛

    private GameRound gameround;
    private int sum;
    private int factor1 = 0;
    private int factor2 = 0;
    private TenPlusModuleRuntimeData runtimeData;

    private AllotSheepFeatherPosition factor1Points;
    private AllotSheepFeatherPosition factor2Points;
    private AllotSheepFeatherPosition resultPoints;

    private GameObject config;

    private GameObject Ledi;
    private Animator lediAni;

    private GameObject featherGarbageStation;

    private GameObject sahuaObj;

    private float lastOperateTime;

    private Camera cacheCam;
   // float scale = 0.5f;

   // Vector3 fix = new Vector3(0, -14f, 0f);
    public CutSheepFeather(GameRound r, int s, TenPlusModuleRuntimeData trd)
    {
        Reset(r,s,trd);
    }
    #region 加载

    public void Reset(GameRound r, int s, TenPlusModuleRuntimeData trd)
    {
        gameround = r;
        runtimeData = trd;
        sum = s;
        factor1 = UnityEngine.Random.Range(1, s);
        factor2 = s - factor1;
        Debug.Log(string.Format("加法算式:{0}+{1}={2}", factor1, factor2, s));

        featherGarbageStation = new GameObject("featherGarbageStation");

        Resource resource;
        resource = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.SheepFeatherCutConfig, typeof(GameObject), enResourceType.Prefab);
        if (config == null)
            config = GameObject.Instantiate(resource.m_content) as GameObject;

        //1.加载场景资源
        LoadScene();

        //2.加载羊群出生点.羊毛点
        LoadConfigData();
        
        //4.初始化勋章个数
        LoadHonor();

        //5.加载羊
        LoadSheep();

        //6.加载乐迪
        LoadLedi();

        //7.注册事件
        Register();

        //8.游戏开始
        GameStart();
    }

    //加载乐迪
    void LoadLedi()
    {
        if (Ledi == null)
        {
            Ledi = new GameObject("ledi(2)");
            Resource r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.ledi, typeof(GameObject), enResourceType.Prefab);
            GameObject lediModel = GameObject.Instantiate(r.m_content) as GameObject;
            lediModel.transform.SetParent(Ledi.transform);
            lediAni = lediModel.GetComponent<Animator>();
            Ledi.transform.position = config.transform.Find("ledi/1").position;
            Ledi.transform.localRotation = config.transform.Find("ledi/1").localRotation;
        }
    }

    //加载场景
    void LoadScene()
    {
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.cutSheepFeatherScene, typeof(GameObject), enResourceType.ScenePrefab);
        if (sceneObj == null)
            sceneObj = GameObject.Instantiate(r.m_content) as GameObject;
        sceneObj.SetActive(true);

        cacheCam = sceneObj.GetComponentInChildren<Camera>();
    }

    //加载配置数据
    void LoadConfigData()
    {
        if (sheepSpawn == null)
            sheepSpawn = config.transform.Find("scene02_sheepSpawnPos").gameObject;
    }

    void ConfigFeatherPoints(HUIEvent hUIEvent)
    {
        Vector2 screenPoint = new Vector2(hUIEvent.m_eventParams.argFloat, hUIEvent.m_eventParams.argFloat2);
        float width = hUIEvent.m_eventParams.argInt;
        float height = hUIEvent.m_eventParams.argInt2;
        float perw = width / 5;
        float z = sheepList[0].transform.position.z;
        factor1Points = new AllotSheepFeatherPosition(factor1, 5, new Rectangle(new Vector2(screenPoint.x - perw*2, screenPoint.y), perw, height),z);
        factor2Points = new AllotSheepFeatherPosition(factor2, 5, new Rectangle(new Vector2(screenPoint.x, screenPoint.y), perw, height), z);
        resultPoints = new AllotSheepFeatherPosition(sum, 5, new Rectangle(new Vector2(screenPoint.x + perw*2, screenPoint.y), perw, height), z);

    }

    //加载算式
    void LoadEquation()
    {
        HUIEvent huievent = new HUIEvent();
        huievent.m_eventID = enUIEventID.AddPlus_Load_Equation;
        string argStr = string.Format("{0},{1},{2}", factor1, factor2, sum);
        huievent.m_eventParams.argString = argStr;
        HUIEventManager.Instance.DispatchUIEvent(huievent);
        
    }

    //加载羊毛UI位置信息
    void LoadFeatherUIPos()
    {
        HUIEvent huievent = new HUIEvent();
        huievent.m_eventID = enUIEventID.AddPlus_FeatherInit;
        huievent.m_eventParams.argInt = factor1;
        huievent.m_eventParams.argInt2 = factor2;
        huievent.m_eventParams.togleIsOn = gameround.sheepTypes == 1 ? true : false;
        HUIEventManager.Instance.DispatchUIEvent(huievent);
    }

    //加载勋章
    void LoadHonor()
    {
        HUIEvent param = new HUIEvent();
        param.m_eventID = enUIEventID.AddPlus_Image_XunZhangAdd;
        param.m_eventParams.argInt = runtimeData.currentRoundIndex;
        HUIEventManager.Instance.DispatchUIEvent(param);
    }

    //加载羊
    void LoadSheep()
    {
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.sheepModule, typeof(GameObject), enResourceType.Prefab);
        int i = 0;
        int sheepNum = Random.Range(5, 10);
        for (; i < sheepNum; i++)
        {

            GameObject sheep = GameObject.Instantiate(r.m_content) as GameObject;
            Transform tran = sheepSpawn.transform.GetChild(i);
            if (gameround.sheepTypes == 2)
            {
                if (i < (sheepNum+1)/2)
                {
                    sheep.AddComponent<SheepModule>().Set(SheepType.whiteSheepWithFeather, tran.position,this, i * 1f);
                }
                else
                {
                    sheep.AddComponent<SheepModule>().Set(SheepType.graySheepWithFeather, tran.position, this, i * 1f);
                }
            }
            else
                sheep.AddComponent<SheepModule>().Set(SheepType.whiteSheepWithFeather, tran.position, this, i * 1f);


            sheep.GetComponent<SheepModule>().HideEffect();
            sheep.transform.localScale = Vector3.one;
            sheep.transform.position = tran.position;
            sheep.GetComponent<Collider>().enabled = false;
            sheepList.Add(sheep);
        }
    }
    

    //注册事件
    void Register()
    {
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.AddPlus_SheepFeather_Cuted, FeatherCuted);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.AddPlus_RoundOver, this.RoundOver);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.AddPlus_ConfigFeatherPoints, this.ConfigFeatherPoints);
       
    }

    //注销事件
    void RemoveLisenter()
    {
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.AddPlus_SheepFeather_Cuted, FeatherCuted);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.AddPlus_RoundOver, this.RoundOver);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.AddPlus_ConfigFeatherPoints, this.ConfigFeatherPoints);
        
    }

    #endregion

    #region 超时处理

    /// <summary>
    /// 开启总计时器
    /// </summary>
    void StartTimer()
    {
        lastOperateTime = Time.realtimeSinceStartup;
        TimerManager.Instance.AddTimer(100, int.MaxValue, Detect);
    }

    void UpdateOperateTime(HUIEvent hUIEvent)
    {
        Updatetime();
    }

    void Updatetime()
    {
        lastOperateTime = Time.realtimeSinceStartup;
    }


    private void Detect(int timerSequence)
    {
        if (Time.realtimeSinceStartup - lastOperateTime > TenPlusModuleAssetPath.timeout)
        {
            Debug.Log("超时了.");
            lastOperateTime = Time.realtimeSinceStartup;
            //我们一起剪羊毛吧
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030207);

        }
    }

    void RemoveTimer()
    {
        TimerManager.Instance.RemoveTimer(this.Detect);
    }

    #endregion

    #region 流程

    //游戏开始
    void GameStart()
    {
        //限定:第一个回合有乐迪提示
        if (runtimeData.currentRoundIndex == 0)
        {
            //乐迪
            //播放音乐&乐迪动画
            //乐迪离开
            //手势指引

            StartIndtroduce();
        }
        else
        {
            EnableSheep();
        }
    }

    //开场介绍 music&乐迪介绍动画
    void StartIndtroduce()
    {
        Vector3 endPos = config.transform.Find("ledi/2").position;
        Ledi.transform.DOMove(endPos, TenPlusAnimLength.lediEnterTime).SetEase(Ease.Flash).OnComplete(() =>
        {
            //播放动画
            lediAni.CrossFade(TenPlusModuleAssetPath.anim_ledi_happy, TenPlusAnimLength.animationCrossTime);
            float showtime = AddPlusController.GetAudioClipLength(TenPlusModuleAssetPath.audio_403030201);
            float anitime = AddPlusController.GetAnimationClipLength(lediAni.runtimeAnimatorController, TenPlusModuleAssetPath.anim_ledi_happy) + 0.2f;
            showtime = showtime > anitime ? showtime : anitime;
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030201);
            TimerManager.Instance.AddTimer(showtime, HideLedi);
        });
    }

    void HideLedi()
    {
        Vector3 endPos = config.transform.Find("ledi/1").position;
        
        Ledi.transform.DOMove(endPos, TenPlusAnimLength.lediExitTime).SetEase(Ease.Flash).OnComplete(() =>
        {
            EnableSheep();
        });

    }

    void EnableSheep()
    {
        //3.加载算式
        LoadEquation();

        //加载羊毛UI位置信息
        LoadFeatherUIPos();
        //算式因子1的羊毛置位0
        factor1 = 0;

        //播音乐要按订单剪羊毛哦
        foreach (GameObject go in sheepList)
        {
            go.GetComponent<Collider>().enabled = true;
            if (runtimeData.currentRoundIndex == 0)
                go.GetComponent<SheepModule>().ShowBoWen();
        }
        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030202);
    }



    //有新剪得羊毛
    public void FeatherCuted(HUIEvent hUIEvent)
    {
        string[] list = hUIEvent.m_eventParams.argString.Split(',');
        Vector3 hitPoint = new Vector3(float.Parse(list[0]), float.Parse(list[1]), float.Parse(list[2]));
        if (gameround.sheepTypes == 1)
        {
            if (factor1 > 0)
            {
                factor1--;
                //算式因子1的位置羊毛+1
                FeatherAdd(1,1,hitPoint);
            }
            else if (factor2 > 0)
            {
                factor2--;
                //算式因子2的羊毛+1
                FeatherAdd(2,1,hitPoint);
            }
            
           
        }
        else
        {
            int sheepType = hUIEvent.m_eventParams.argInt;
            if (sheepType <= 2)
            {
                //白羊
                if (factor1 > 0)
                {
                    factor1--;
                    //因子1位置白羊毛+1
                    FeatherAdd(1,1,hitPoint);
                }
            }
            else
            {
                //灰羊
                if (factor2 > 0)
                {
                    factor2--;
                    //因子2位置灰羊毛+1
                    FeatherAdd(2,2,hitPoint);
                }
            }
            
        }
    }

    /// <summary>
    /// 加羊毛
    /// </summary>
    /// <param name="pos">在因子1还是因子2</param>
    /// <param name="color">1代表白色，2代表灰色</param>
    /// <param name="hitPoint"></param>
    void FeatherAdd(int pos,int color,Vector3 hitPoint)
    {
        //GameObject feather;
        //Resource r;
        //Vector3 position;

        AudioClip[] audioClips = new AudioClip[2];
        audioClips[0] = AudioManager.Instance.GetAudioClip(TenPlusModuleAssetPath.audio_603030101);//绵羊叫
        audioClips[1] = AudioManager.Instance.GetAudioClip(TenPlusModuleAssetPath.audio_603030201);//羊毛移动
        AudioManager.Instance.PlaySound(audioClips);

        HUIEvent hUIEvent = new HUIEvent();
        hUIEvent.m_eventID = enUIEventID.AddPlus_FeatherAdd;
        hUIEvent.m_eventParams.argInt2 = color;
        Vector3 screenPoint = cacheCam.WorldToScreenPoint(hitPoint);
        hUIEvent.m_eventParams.argString = string.Format("{0},{1},{2}", screenPoint.x, screenPoint.y, screenPoint.z);
        if (pos == 1)
        {

            //r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.whiteSheepFeather, typeof(GameObject), enResourceType.Prefab);
            //feather = GameObject.Instantiate(r.m_content) as GameObject;
            //feather.transform.SetParent(featherGarbageStation.transform);
            //feather.transform.position = hitPoint;
            //position = factor1Points.GetPos(featherList1.Count,cacheCam)+fix;




            //featherList1.Add(feather);

            //feather.transform.localScale = Vector3.one * 4;
            //feather.transform.DOScale(scale, TenPlusAnimLength.featherEntertime).SetEase(Ease.Flash);
            //Tweener tweener = feather.transform.DOMove(position, TenPlusAnimLength.featherEntertime).SetEase(Ease.Flash).OnComplete(()=> 
            //{
            //    IsLeftFeatherFull();
            //});


            hUIEvent.m_eventParams.argInt = 0;
            
            IsLeftFeatherFull();

        }
        else
        {
            //if (color == 2)
            //    r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.graySheepFeather, typeof(GameObject), enResourceType.Prefab);
            //else
            //    r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.whiteSheepFeather, typeof(GameObject), enResourceType.Prefab);
            //feather = GameObject.Instantiate(r.m_content) as GameObject;
            //feather.transform.SetParent(featherGarbageStation.transform);
            //feather.transform.position = hitPoint;
            //
            //position = factor2Points.GetPos(featherList2.Count,cacheCam)+fix;
            //
            //featherList2.Add(feather);
            //feather.transform.localScale = Vector3.one * 4;
            //feather.transform.DOScale(scale, TenPlusAnimLength.featherEntertime).SetEase(Ease.Flash);
            //Tweener tweener = feather.transform.DOMove(position, TenPlusAnimLength.featherEntertime).SetEase(Ease.Flash).OnComplete(()=> 
            //{
            //    IsLeftFeatherFull();
            //});

            hUIEvent.m_eventParams.argInt = 1;

            IsLeftFeatherFull();
        }


        HUIEventManager.Instance.DispatchUIEvent(hUIEvent);
    }

    //左边的羊毛是否已经齐活
    void IsLeftFeatherFull()
    {
        if (gameround.sheepTypes == 1)
        {
            //一种羊
            if (factor1 == 0 && factor2 == 0)
                ResultFeatherShow();
        }
        else
        {
            //两种羊
            if (factor1 == 0 && factor2 == 0)
                ResultFeatherShow();
        }
    }

    void ResultFeatherShow()
    {
        //音效：你真棒，我们继续吧.
        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030204);

        //GameObject feather;
        //Resource r;
        //Vector3 position;
        //int i = 0;
        //for (; i < featherList1.Count; i++)
        //{
        //    r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.whiteSheepFeather, typeof(GameObject), enResourceType.Prefab);
        //    feather = GameObject.Instantiate(r.m_content) as GameObject;
        //    position = resultPoints.GetPos(featherList.Count,cacheCam) + fix;
        //    feather.transform.position = position;
        //    feather.transform.localScale = new Vector3(scale,scale,scale);
        //    feather.transform.SetParent(featherGarbageStation.transform);
        //    featherList.Add(feather);
        //}
        //
        //for (i = 0; i < featherList2.Count; i++)
        //{
        //    if (gameround.sheepTypes == 2)
        //        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.graySheepFeather, typeof(GameObject), enResourceType.Prefab);
        //    else
        //        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.whiteSheepFeather, typeof(GameObject), enResourceType.Prefab);
        //
        //    feather = GameObject.Instantiate(r.m_content) as GameObject;
        //    position = resultPoints.GetPos(featherList.Count,cacheCam) + fix;
        //    feather.transform.position = position;
        //    feather.transform.localScale = new Vector3(scale, scale, scale);
        //    feather.transform.SetParent(featherGarbageStation.transform);
        //    featherList.Add(feather);
        //}



        LockSheepclick();
        DispatchShowRightFeather();
        DispatchXunzhangAnim();
    }

    void LockSheepclick()
    {
        foreach (GameObject go in sheepList)
            go.GetComponent<SheepModule>().LockClick();
    }

    //羊毛右边结果展示
    void DispatchShowRightFeather()
    {
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.AddPlus_FeatherRightShow, new stUIEventParams { argInt = gameround.sheepTypes  });
    }

    void DispatchXunzhangAnim()
    {
        //发送勋章+1的消息
        HUIEvent ev = new HUIEvent();
        ev.m_eventID = enUIEventID.AddPlus_StartMove_Xunzhang;
        ev.m_eventParams.argInt = runtimeData.currentRoundIndex + 1;
        HUIEventManager.Instance.DispatchUIEvent(ev);
    }

    public void RoundOver(HUIEvent huiEvent)
    {
        //回合结束
        float time = AddPlusController.GetAudioClipLength(TenPlusModuleAssetPath.audio_403030206);
        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030206);
        TimerManager.Instance.AddTimer(time, ()=> 
        {
            //显示击掌交互
            HideCardAndFeather();
        });
    }

    //是否需要击掌交互
    bool IsNeedClapInteractive()
    {
        if (runtimeData.currentRoundIndex == 3)
            return true;
        else
            return false;
    }


    //隐藏卡牌和羊毛
    void HideCardAndFeather()
    {
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.AddPlus_HideEquation);
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.AddPlus_FeatherDestroy);
        featherGarbageStation.transform.DOMove(featherGarbageStation.transform.position + new Vector3(0f, -500f, 0f), TenPlusAnimLength.featherExitTime)
            .SetEase(Ease.Flash).OnComplete(()=> 
            {
                //回合结束
                if (IsNeedClapInteractive())
                {
                    Clap();
                }
                else
                {
                    TheEnd();
                }
            });
    }

    //是否需要击掌
    void Clap()
    {
        //加载乐迪击掌模型
        //击掌特效
        //等待击掌
        Ledi.SetActive(true);
        Ledi.transform.position = config.transform.Find("ledi/2").position;
        lediAni.SetBool("enterClap", true);
        float clapAnimLength = AddPlusController.GetAnimationClipLength(lediAni.runtimeAnimatorController, TenPlusModuleAssetPath.anim_ledi_clap);
        TimerManager.Instance.AddTimer(clapAnimLength, ShowClapBowen);
    }

    void ShowClapBowen()
    {
        GameObject effect = Ledi.transform.GetChild(0).Find("Effect").gameObject;
        effect.SetActive(true);
        effect.AddComponent<AddPlusLedi>().Setup(ClapOver);
    }

    void ClapOver()
    {
        GameObject effect = Ledi.transform.GetChild(0).Find("Effect").gameObject;
        effect.SetActive(false);
        GameObject.Destroy(effect.GetComponent<AddPlusLedi>());
        lediAni.CrossFade(TenPlusModuleAssetPath.anim_ledi_clap2, TenPlusAnimLength.animationCrossTime);
        //音效 啪
        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_603030501);
        //撒花特效
        FlowerShow();
    }

    void FlowerShow()
    {
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.sahua, typeof(GameObject), enResourceType.Prefab);
        sahuaObj = GameObject.Instantiate(r.m_content) as GameObject;
        sahuaObj.transform.position = config.transform.Find("sahua").transform.position;

        TimerManager.Instance.AddTimer(1f, TheEnd);
    }


    void TheEnd()
    {
        DoClean();
        //发送 游戏数据改变信息
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.AddPlus_GameProcedure_Change);
    }

    //判定一种羊毛是否可以剪
    public bool CanyouCutSheepFeather(int sheepColor)
    {
        if (gameround.sheepTypes == 1)
        {
            if (factor1 == 0 && factor2 == 0)
                return false;
            else
                return true;
        }
        else
        {
            if (sheepColor <= 2)
            {
                //白羊
                return factor1 == 0 ? false : true;
            }
            else
            {
                //灰羊
                return factor2 == 0 ? false : true;
            }
        }
    }


    #endregion


    #region 善后
    public void HideScene()
    {
        if (sceneObj != null) sceneObj.SetActive(false);
    }

    public void DoClean()
    {
        TimerManager.Instance.RemoveAllTimer();
        GameObject.DestroyImmediate(featherGarbageStation);
        DestroySheep();
        DestroyFeather();
        RemoveLisenter();
        GameObject.DestroyImmediate(Ledi);
        GameObject.DestroyImmediate(sahuaObj);
    }

    void DestroySheep()
    {
        foreach (GameObject go in sheepList)
            GameObject.DestroyImmediate(go);
        sheepList.Clear();
    }

    void DestroyFeather()
    {
        foreach (GameObject go in featherList1)
            GameObject.DestroyImmediate(go);
        featherList1.Clear();
        foreach (GameObject go in featherList2)
            GameObject.DestroyImmediate(go);
        featherList2.Clear();
        foreach (GameObject go in featherList)
            GameObject.DestroyImmediate(go);
        featherList.Clear();
    }
    #endregion

    #region 辅助类

    //绵羊位置分配 [x,y]平面
    class AllotSheepFeatherPosition
    {
        float z;

        //占位绵羊数量
        public int num;

        //每行最大数量
        public int maxNumOneRow;

        //生成的占位点List
        public List<Vector2[]> list = new List<Vector2[]>();

        public List<Vector2> V2List = new List<Vector2>();
        //限制盒 点集
        public List<Vector2> limitBoxList = new List<Vector2>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="n">总数量</param>
        /// <param name="mnor">每行最大数量</param>
        /// <param name="parentTran"></param>
        public AllotSheepFeatherPosition(int n, int mnor, List<Vector2> lbl, float axisz)
        {
            num = n;
            maxNumOneRow = mnor;
            limitBoxList = lbl;
            z = axisz;
            Init();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="n"></param>
        /// <param name="mnor"></param>
        /// <param name="lbl"></param>
        /// <param name="axisz"></param>
        public AllotSheepFeatherPosition(int n, int mnor,Rectangle r,float axisz)
        {
            num = n;
            maxNumOneRow = mnor;
            limitBoxList = r.GetAngles();
            z = axisz;
            Init();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="n">总数量</param>
        /// <param name="mnor">每行最大数量</param>
        /// <param name="parentTran"></param>
        public AllotSheepFeatherPosition(int n, int mnor, Transform parentTran)
        {
            num = n;
            maxNumOneRow = mnor;
            List<Vector2> lbl = new List<Vector2>();
            for (int i = 0; i < parentTran.childCount; i++)
            {
                lbl.Add(parentTran.GetChild(i).position.Vector3ToVector2_XY());
            }
            limitBoxList = lbl;
            z = parentTran.GetChild(0).position.z;
            Init();
        }

        void Init()
        {
            Vector2 min = limitBoxList[0];
            Vector2 max = limitBoxList[0];
            foreach (Vector2 v2 in limitBoxList)
            {
                min.x = min.x < v2.x ? min.x : v2.x;
                min.y = min.y < v2.y ? min.y : v2.y;
                max.x = max.x > v2.x ? max.x : v2.x;
                max.y = max.y > v2.y ? max.y : v2.y;
            }

            //Vector2 center = new Vector2((min.x + max.x) / 2, (min.y + max.y) / 2);
            //float width = max.x - min.x;
            //float height = max.y - min.y;

            int row = num / maxNumOneRow + (num % maxNumOneRow == 0 ? 0 : 1);

            float heightPerRow = (max.y - min.y) / row;//行高
            

            for (int i = 0; i < row; i++)
            {
                int startIndex = (row - i - 1) * maxNumOneRow;
                int endIndex = (row - i - 1 + 1) * maxNumOneRow;
                endIndex = endIndex > (num - 1) ? (num - 1) : endIndex;
                int thisColNum = endIndex - startIndex + 1;
                Vector2[] ele = new Vector2[thisColNum];
                float widthPerRow = (max.x - min.x) / thisColNum;
                //起点(minx,maxy)
                for (int j = 0; j < ele.Length; j++)
                {
                    float x = 0.5f * widthPerRow + j * widthPerRow + min.x;
                    float y = -0.5f * heightPerRow - i * heightPerRow + max.y;
                    ele[j] = new Vector2(x, y);
                    V2List.Add(new Vector2(x, y));
                    //Debug.Log(new Vector2(x, y));
                }
                list.Add(ele);
            }
        }

        public Vector3 GetPosInScreen(int index)
        {
            return V2List[index].Vector2ToVector3_XY(z);
        }


        public Vector3 GetPos(int index,Camera cam)
        {
            return cam.ScreenToWorldPoint(V2List[index].Vector2ToVector3_XY(z));
        }
    }

    #endregion
}
